﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Seagull.Controls
{
    public class CheckButtonGroup : IEnumerable<CheckBox>
    {
        private readonly HashSet<CheckBox> _buttons =
            new HashSet<CheckBox>();

        public void Add(CheckBox button)
        {
            _buttons.Add(button);
            button.Click += button_Click;
        }

        public void Remove(CheckBox button)
        {
            button.Click -= button_Click;
            _buttons.Remove(button);
        }

        void button_Click(object sender, EventArgs e)
        {
            var clickedButton = (CheckBox)sender;
            if(clickedButton.Checked)
            {
                return;
            }

            foreach(var button in _buttons)
            {
                button.Checked = false;
            }
            clickedButton.Checked = true;
        }

        #region Implementation of IEnumerable

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public IEnumerator<CheckBox> GetEnumerator()
        {
            return _buttons.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}
